/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.fatecpg.songs.intranet.managedbeans;

import br.com.fatecpg.songs.crud.facade.RegisterFacade;
import br.com.fatecpg.songs.dao.util.DAOException;
import br.com.fatecpg.songs.entity.User;
import br.com.fatecpg.songs.entity.util.UserStatus;
import br.com.fatecpg.songs.util.FacesContextUtil;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import org.hibernate.exception.ConstraintViolationException;

/**
 *
 * @author Marcos
 */
@ManagedBean
@ViewScoped
public class UserManagedBean implements RegisterManagedBean<User>{
    
    private int viewState;
    private final RegisterFacade<User> facade = new RegisterFacade<User>(User.class);       
    private User user;    
    private List<User> list;

    public UserManagedBean() throws DAOException {
        viewState = LIST_STATE;
        user = new User();                
        list = facade.list();
    }    
                      
    @Override
    public void openNew() {
        user = new User();
        viewState = REGISTER_STATE;
    }

    @Override
    public void openToUpdate() throws DAOException {               
        this.user = facade.load();
        this.viewState = REGISTER_STATE;
    }

    @Override
    public void register() throws DAOException {
        try{
            user.setUserStatus(UserStatus.Y);
            facade.register(user);
            list = facade.list();
            viewState = LIST_STATE;            
        }catch(ConstraintViolationException ex){
            FacesContextUtil.addMessage("Já existe um usuário com este login.");
        }
    }

    @Override
    public void delete() throws DAOException {                
        deactive();
    }
    
    public void active() throws DAOException{
        facade.active();
        list = facade.list();
        this.viewState = LIST_STATE;
    }
    
    public void deactive() throws DAOException{
        facade.deactive();        
        list = facade.list();
        this.viewState = LIST_STATE;
    }   

    @Override
    public void cancel() {        
        this.user = new User();
        this.viewState = LIST_STATE;
    }
    
    @Override    
    public List<User> getList() {        
        return list;
    }
       
    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public int getViewState() {
        return viewState;
    }

    public void setViewState(int viewState) {
        this.viewState = viewState;
    } 
}
